from django.shortcuts import render, redirect
from publish.models import Publish, PublishAdmin
from author.models import Author
from utils.LoginForm import LoginForm
from publish.publish_utils.PublishForm import PublishForm
from utils.MyPage import Pagination


# Create your views here.
def main(request):
    return render(request, 'publish_main.html')


def edit_info(request):
    return render(request, 'publish_edit_info.html')


def edit_author(request):
    publish_obj = Publish.objects.get(pk=1)
    author_obj_all = Author.objects.filter(publish_id=1)
    return render(request, 'publish_edit_author.html', locals())


def check_info(request):
    current_page = request.GET.get('page', 1)
    publish_obj_all = Publish.objects.all()
    all_count = publish_obj_all.count()
    page_obj = Pagination(current_page=current_page, all_count=all_count, per_page_num=5, pager_count=5)
    publish_obj = publish_obj_all[page_obj.start:page_obj.end]
    page_html = page_obj.page_html()
    return render(request, 'author_publish.html', locals())


def register(request):
    login_form = LoginForm()
    publish_form = PublishForm()
    if request.method == 'POST':
        data = request.POST
        login_form = LoginForm(data)
        login_form.fields['username'].validators[1].table = 'publish'
        publish_form = PublishForm(data)
        is_identity_login = login_form.is_valid()
        is_identity_publish = publish_form.is_valid()
        if is_identity_login and is_identity_publish:
            publish_admin, publish_info = handle_data(data)
            publish_obj = Publish.objects.create(**publish_info)
            publish_login = PublishAdmin.objects.create(**publish_admin, publish=publish_obj)
            return render(request, 'publish_main.html')

    return render(request, 'publish_register.html', locals())


def handle_data(data):
    publish_admin = {
        'username': data.get('username'),
        'password': data.get('password'),
    }
    publish_info = {
        'name': data.get('name'),
        'email': data.get('email'),
        'addr': data.get('addr'),
        'desc': data.get('desc'),
    }
    return publish_admin, publish_info
